/**
 * Created by xxx on 2017/7/12.
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'

import Header from './Common/Header'
import Footer from './Common/Footer'
import LoadingBox from './Common/LoadingBox'
import ConfirmBox from './Common/ConfirmBox'

import {
    HttpService,
    getLocalTime,
    Tips,
    AjaxUploadImgUrl,
    viewerImg,
    getDefaultImg,
    lazyLoad,
    specialStr,
    taskFinish,
    iosfocus,
    iosblur,
    browser
} from '../Tools'

import downBlue from '../Img/icon/down_blue3.png'
import likeBlue from '../Img/icon/like_blue.png'
import likeBlueSolid from '../Img/icon/like_blue_solid.png'
import review from '../Img/icon/review.png'
import addRoundBlue from '../Img/icon/add_round_blue.png'
import lazyImg from '../Img/other/albumDefault.png';
/*
 *班级相册-教师、家长
 */
export default class AlbumDetail extends Component {
    constructor(props) {
        super(props);
        this.config = {};
        this.page = 1;
        this.pagesize = 5;
        this.toBottom = 100;
        this.courseName = '';
        this.allDataList = [];
        this.photoid = '';
        this.tempphotoid = this.props.params.photoid;
        this.fileRemark = '';
        this.dataLoad = 1;
        this.replayShow = true;
        this.state = {
            dataList: [],
            dataLoad: 1,
            footer: false,
            dataEnd: 0,
            dataNull: 0,
            show: 0,
            comment: 0,
            ismyself: false,
            photoView: false,
            sigle: 0
        }
    }
    componentWillMount() {
        this.getData();
        this.replayShow = false;
    }

    componentDidMount() {
        window.onscroll = () => {
            if (this.dataLoad == 1 || sessionStorage.interval)
                return;
            const {
                dataLoad,
                dataEnd,
                dataNull
            } = this.state;
            if (dataLoad == 1 || dataEnd == 1 || dataNull == 1)
                return;
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
            if (document.body.clientHeight - window.innerHeight - scrollTop <= this.toBottom) {
                this.page++;
                this.getData();
            }
        }
    }

    //点赞1/0
    loveAlbum(photoId, e) {
        let imgObj = e.currentTarget.children[0],
            zanObj = e.currentTarget.children[1];
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookDealer.do',
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_402SayGood',
                photoId
            },
            success: (res => {
                if (res.code == 0) {
                    Tips('点赞成功', 1);
                    let num = parseInt(zanObj.innerHTML);
                    if (num == 0)
                        imgObj.src = likeBlueSolid
                    zanObj.innerHTML = ++num;
                } else if (res.code == 1) {
                    Tips('已经点过赞了', 1);
                } else {
                    Tips('点赞失败', 1);
                }
            })
        })
    }

    //评论显示/隐藏
    commentView(comment, id) {
        if (comment == 0) {
            document.getElementById('cmtxt').blur();
            document.getElementById('cmtxt').value = '';
        } else {
            document.getElementById('cmtxt').focus();
        }
        this.setState({
            comment
        });
        if (id) {
            this.photoId = id
        }
    }
    //提交评论
    commentPublish(e) {
        e.preventDefault();
        const comment = document.getElementById('cmtxt').value;
        if (comment == '') {
            Tips('请输入评论内容');
            return;
        }
        if (comment.length > 50) {
            Tips('评论内容已超过50字');
            return;
        }
        // if (specialStr(comment)) {
        //     Tips('评论内容不支持特殊字符');
        //     return;
        // }
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookDealer.do',
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_301Comment',
                photoId: this.photoId.split('&')[0],
                comment
            },
            success: (res => {
                if (res.code == 0) {
                    Tips('评论成功', 1);
                    let addCmt = this.state.dataList;
                    addCmt[this.photoId.split('&')[1]].comments.push(res.r)
                    this.setState({
                        comment: 0,
                        dataList: addCmt
                    })
                    document.getElementById('cmtxt').value = '';
                    document.getElementById('cmtxt').blur();
                    if (sessionStorage.userrole == '家长') {
                        taskFinish('评价相册', (status, config) => {
                            if (status) {
                                this.config = config;
                                this.setState({
                                    sigle: 1,
                                    show: 1
                                })
                            }
                        })
                    }
                } else {
                    Tips('评论失败')
                }
            })
        })
    }
    //获取评论
    commentDataList(photoId, callback) {
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookQuery.do',
            async: false,
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'ajaxJybJSON_302ListComment',
                page: 1,
                pagesize: 100,
                photoId
            },
            success: (res => {
                let data = []
                if (res.code == 0) {
                    if (res.r.comments.length == 0) {
                        data = []
                    } else {
                        data = res.r.comments.reverse()
                    }
                } else {
                    data = [];
                }
                callback(data)
            })
        })
    }

    //获取列表
    getData() {
        this.dataLoad = 1;
        this.setState({
            dataLoad: 1,
            dataEnd: 0,
            dataNull: 0
        });
        let data = {
            jybTicket: sessionStorage.ticket,
            method: 'ajaxJybJSON_001QryBookPhoto',
        };
        if (this.tempphotoid) {
            data.method = 'ajaxJybJSON_001QryBookPhotoDetail';
            data.photoid = this.tempphotoid
        } else {
            data.page = this.page;
            data.pagesize = this.pagesize;
            data.properties = 'creatorName,createDate,ismyself,sayGoodPersonCount';
            data.bookid = this.props.params.id
        }
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookQuery.do',
            data,
            //async: false,
            success: (res => {
                if (res == '') {
                    Tips('该图片已被删除');
                    this.setState({
                        dataLoad: 0,
                        dataNull: 1
                    });
                    return;
                }
                if (res.code == 0) {
                    let data = res.rs || res.r.photo;
                    if (!(data instanceof Array)) {
                        let arr = [];
                        arr.push(data);
                        data = arr
                    }
                    console.log(data);
                    let dataEnd = 0,
                        dataNull = 0;
                    data.map((item, index) => {
                        this.commentDataList(item.id, (data) => {
                            item.comments = data;
                        });
                    });
                    if (data.length < this.pagesize) {
                        dataEnd = 1;
                        if (data.length == 0 && this.page == 1) {
                            dataEnd = 0;
                            dataNull = 1
                        }
                    }
                    let newData = this.state.dataList.concat(data);
                    //setTimeout(() => {
                    this.setState({
                        dataList: newData,
                        dataLoad: 0,
                        dataEnd,
                        dataNull
                    });
                    lazyLoad(document.querySelector('.list'));
                    //}, 200);
                    return;
                }
                Tips(res.msg);
            })
        })
    }

    //相册介绍
    AlbumIntro() {
        this.config = {
            sign: 1,
            title: '相册介绍',
            content: decodeURIComponent(this.props.params.content),
            cancelName: '知道了'
        };
        this.setState({
            footer: false,
            sigle: 1,
            show: 1
        })
    }
    //相册删除
    AlbumDelete() {
        this.config = {
            sign: 2,
            title: '温馨提示',
            content: '确定要删该相册吗？',
            cancelName: '取消'
        };
        this.setState({
            footer: false,
            sigle: 0,
            show: 1
        });
    }
    //底部弹框显示
    FooterOpen() {
        this.setState({
            footer: !this.state.footer,
            photoView: false
        })
    }
    //底部弹框关闭
    FooterClose() {
        this.setState({
            footer: false
        })
    }
    //关闭confirmBox
    cfmCancel() {
        this.setState({
            show: 0
        })
    }
    //确定删除
    cfmSure() {
        this.setState({
            footer: false,
            show: 0
        })
        const sign = this.config.sign
        if (sign == 1) {
            return
        }

        const {
            id,
            classid
        } = this.props.params;
        let data = {
            jybTicket: sessionStorage.ticket,
            method: 'ajaxJybJSON_101DeleteClassPhotoBook',
            bookid: id,
            classid
        }
        if (sign == 2) { //删除相册
            data.classid = classid
        } else if (sign == 3) { //删除照片
            data.method = 'ajaxJybJSON_101DeletePhotoFromBook'
            data.photoids = this.photoid
        }
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookDealer.do',
            data,
            success: (res => {
                if (res.code == 0) {
                    if (sign == 2) {
                        hashHistory.go(-1)
                    } else if (sign == 3) { //删除照片后初始化数据
                        this.page = 1;
                        this.setState({
                            dataList: [],
                            dataLoad: 1
                        })
                        this.getData();
                    }
                } else {
                    Tips(res.msg ?
                        res.msg :
                        '删除失败');
                }
            })
        })
    }
    // //相册显示自我数据处理
    // photoMyselfData() {
    //     let newDataList = [];
    //     if (this.state.ismyself == false) {
    //         newDataList = this.allDataList;
    //     } else {
    //         this.allDataList.map((item, index) => {
    //             if (item.ismyself == true)
    //                 newDataList.push(item)
    //         })
    //     }
    //     this.setState({dataList: newDataList});
    // }
    //
    // //仅显示我的
    // AlbumMyself(e) {
    //     this.setState({
    //         footer: false,
    //         ismyself: !this.state.ismyself
    //     });
    //     this.photoMyselfData();
    // }
    //折叠盒子
    foldBox(id, index, e) {
        let oldWord = e.currentTarget.innerHTML,
            oldClass = document.getElementById(id);
        if (oldWord.indexOf('显示') > -1) {
            let cmtsObj = document.querySelectorAll('#commentlist' + index + ' li')
            for (var i = 0; i < cmtsObj.length; i++) {
                cmtsObj[i].style.display = 'block'
            }
            e.currentTarget.innerHTML = oldWord.replace('显示', '收起');
        } else {
            let cmtsObj = document.querySelectorAll('#commentlist' + index + ' li')
            for (var i = 0; i < cmtsObj.length; i++) {
                if (i >= 4)
                    cmtsObj[i].style.display = 'none'
            }
            e.currentTarget.innerHTML = oldWord.replace('收起', '显示');
        }
    }

    //图片删除
    photodelete() {
        this.config = {
            sign: 3,
            title: '温馨提示',
            content: '确定要删该图片吗？',
            cancelName: '取消'
        };
        this.setState({
            footer: false,
            sigle: 0,
            show: 1
        });
    }
    //图片处理框显示
    photoHandle(photoid, fileRemark) {
        this.photoid = photoid
        this.fileRemark = fileRemark
        this.setState({
            footer: true,
            photoView: true
        });
    }

    //苹果手机样式问题
    replyContentFocus() {
        iosfocus()
    }
    replyContentBlur() {
        iosblur()
    }

    //编辑相册后返回
    editBack() {
        hashHistory.go(-3)
    }
    /**
     * 判断图片宽高
     */
    imgOnload(e) {
        if (e.target.width > e.target.height) {
            e.target.parentNode.setAttribute('class', 'lineblock one wid');
        } else {
            e.target.parentNode.setAttribute('class', 'lineblock one hei');
        }


    }
    render() {
        const {
            dataLoad,
            dataEnd,
            dataNull,
            dataList,
            footer,
            show,
            comment,
            photoView,
            ismyself,
            sigle
        } = this.state;
        const tagList = dataList.map((item, index) => {
            const timeStr = getLocalTime(item.createTime);
            let commentHtml = item.comments.map((cmt, cmtindex) => {
                let display = 'block';
                if (cmtindex >= 4 && item.id + '&' + index != this.photoId)
                    display = 'none';
                return (
                    <li style={{
                        display
                    }}>
                        <span className="list_title">{cmt.creatorName}：</span>
                        <span className="list_content">{cmt.comment}</span>
                    </li>
                )
            });
            this.dataLoad = 0;
            return (
                <li className="list_li">
                    <img className="header_img" src={getDefaultImg()}/>
                    <div className="content">
                        <div className="title">
                            <span>{item.creatorName}</span>
                            {sessionStorage.userrole == '班主任' || item.ismyself == true
                                ? <img onClick={this.photoHandle.bind(this, item.id, item.fileRemark)} src={downBlue}/>
                                : ''}
                        </div>
                        {/*<div className="time_info clearfix">*/}
                            {/*<span className="title">{getLocalTime(item.createDate.time?item.createDate.time:item.createDate)}</span>*/}
                        {/*</div>*/}
                        <div className="describe">
                            {item.fileRemark}
                        </div>
                        <div className="photos">
                            {
                                item.fileId.split(',').map((data, i) => {
                                    let lineblock = 'lineblock one';//默认只有一张图片的时候
                                   if(item.fileId.split(',').length==2||item.fileId.split(',').length==4){
                                       switch ((i+1)%2){
                                           case 0:
                                               lineblock = 'lineblock tfRight';
                                               break;
                                           case 1:
                                               lineblock = 'lineblock tfLeft';
                                               break;
                                       }
                                    }else if(item.fileId.split(',').length > 2){
                                        switch ((i+1)%3){
                                            case 0:
                                                lineblock = 'lineblock right';
                                                break;
                                            case 1:
                                                lineblock = 'lineblock left';
                                                break;
                                            case 2:
                                                lineblock = 'lineblock center';
                                                break;
                                        }
                                    }
                                   return (
                                       <label className={lineblock}>
                                           {
                                               lineblock=='lineblock one'?
                                                   <img onClick={viewerImg.bind(this, 'data-viewer')} onLoad={this.imgOnload.bind(this)} data-viewer={AjaxUploadImgUrl + data} data-src={AjaxUploadImgUrl + data} src={lazyImg}/>
                                                   :
                                                   <div className="photo" style={{backgroundImage:'url('+lazyImg+')'}}>
                                                       <img onClick={viewerImg.bind(this, 'data-viewer')} data-viewer={AjaxUploadImgUrl + data}  data-src={AjaxUploadImgUrl + data} src={lazyImg}/>
                                                   </div>
                                           }

                                       </label>
                                   )
                                })
                            }
                        </div>
                        <div className="time_info  clearfix">
                            <span className="title">{getLocalTime(item.createDate.time?item.createDate.time:item.createDate)}</span>
                            <span className="review" onClick={this.commentView.bind(this, 1, item.id + '&' + index)}><img src={review}/>评论</span>
                            <span className="like" onClick={this.loveAlbum.bind(this, item.id)}>
                                <img src={item.sayGoodPersonCount == 0
                                    ? likeBlue
                                    : likeBlueSolid}/>
                                赞(<i>{item.sayGoodPersonCount}</i>)
                            </span>
                        </div>
                        {/*<div className="like_list row_five" id='lovelist'>
                            <img src={likeBlueSolid}/>
                            张三，李四，王五 [无此功能]
                            <div className="show_like" onClick={this.foldBox.bind(this, 'lovelist', 0)}>显示全部点赞</div>
                        </div>*/}
                        {
                            commentHtml != ''
                            ?
                                <div className="reviews">
                                    <span className="online" />
                                    <div className="review_list row_five" id={'commentlist' + index}>
                                        <ul className={'cmmhtml' + index}>{commentHtml}</ul>
                                        {
                                            item.id + '&' + index == this.photoId && item.comments.length > 4
                                                ? <div className="show_review" onClick={this.foldBox.bind(this, 'commentlist' + index, index)}>收起全部评论</div>
                                                : <div>
                                                {item.comments.length > 4
                                                    ? <div className="show_review" onClick={this.foldBox.bind(this, 'commentlist' + index, index)}>显示全部评论</div>
                                                    : ''}
                                            </div>
                                        }
                                    </div>
                                </div>
                            : ''
                        }
                    </div>
                </li>
            )
        })
        const publishLink = <a onClick={this.FooterOpen.bind(this)} className='h_link three_point'/>;
        const {
            id,
            name,
            content,
            classid
        } = this.props.params
        return (
            <div className='album_name clearfix'>
                <Header title={decodeURIComponent(name)} link={this.tempphotoid?null:publishLink} addFn={this.props.params.edit=='true'
                    ? this.editBack.bind(this)
                    : null}/>
                {this.tempphotoid?''
                    :<Link className="add_img" to={'/AddPhoto/' + id}>
                    <img src={addRoundBlue}/>
                </Link>}
                <ul className="list" style={{
                    minHeight: 'initial'
                }}>
                    {tagList}
                </ul>
                <LoadingBox dataLoad={dataLoad} dataEnd={dataEnd} dataNull={dataNull}/> {footer == true
                    ? <div>
                            <div className='maskin' onClick={this.FooterOpen.bind(this)}></div>
                            {photoView == true
                                ? <Footer>
                                        <Link className='fitem' to={'/AddPhoto/' + id + '/' + this.photoid + '/' + encodeURIComponent(this.fileRemark)}>修改描述</Link>
                                        <Link className='fitem' to={'/ClassAlbum/' + id + '/' + this.photoid}>移动图片</Link>
                                        <div className='fitem' onClick={this.photodelete.bind(this)}>删除图片</div>
                                        <div className='fitem' onClick={this.FooterClose.bind(this)}>取消</div>
                                    </Footer>
                                : <Footer>
                                    <Link className='fitem' to={'/AddPhoto/' + id}>上传照片</Link>
                                    <div className='fitem' onClick={this.AlbumIntro.bind(this)}>相册介绍</div>
                                    {sessionStorage.userrole == '班主任'
                                        ? <Link className='fitem' to={'/AddAlbum/' + classid + '/true/' + id + '/' + encodeURIComponent(name) + '/' + encodeURIComponent(content)}>编辑相册</Link>
                                        : ''}
                                    {/*<Link className='fitem' onClick={this.AlbumMyself.bind(this)}>{ismyself == true
                                            ? '显示全部'
                                            : '仅显示我发布的'}</Link>*/}
                                    {sessionStorage.userrole == '班主任'
                                        ? <div className='fitem' onClick={this.AlbumDelete.bind(this)}>删除相册</div>
                                        : ''}
                                    <div className='fitem' onClick={this.FooterClose.bind(this)}>取消</div>
                                </Footer>
}

                        </div>
                    : ''
}

                <ConfirmBox cancel={this.cfmCancel.bind(this)} config={this.config} show={show} sigle={sigle} sure={this.cfmSure.bind(this)}/>
                <div  className='iosinputbox' style={{display:this.replayShow==false?'block':'none',zIndex:comment == 1?'10':'-1',opacity:comment == 1?'1':'0'}}>
                    <div className='mask replay_mask' onClick={this.commentView.bind(this, 0, '')}/>
                    <div className='pjb_commentbox'>
                        <input type='text' ref='comment' autoComplete='off' placeholder='输入评论信息（最多50字）' onBlur={this.replyContentBlur.bind(this)} onFocus={this.replyContentFocus.bind(this)} id='cmtxt'/>
                        <input className='btn' type='button' value='发布' onClick={this.commentPublish.bind(this)} />
                    </div>
                </div>
            </div>
        )
    }
}
